package com.assets.Back;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.*;

import com.assets.Adapter.Input_Adapter_item1;
import com.assets.Adapter.Input_Adapter_item_new;
import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.bean.Input_item1;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Returns;
import com.assets.util.MyRFIDHandle;
import com.assets.util.RFIDClientUtil;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.CanniBalize.Shift_site;
import com.google.gson.Gson;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/12/25.
 */

public class back extends BaseActivity1 {
    private ImageView imageView;
    private TextView site_tv, title_text;
    private String site_id = "";
    private String url = "http://" + Url.IP + "/api/returnsAddInspect";
    private String returnAdd = "http://" + Url.IP + "/api/returnsAdd";
    private ListView lv_list;
    private LinearLayout site;
    private Button uploads;
    private Button scan_img, btn_rfid;//扫码
    private List<Input_item1> data = new ArrayList<>();
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private List<String> numbers = new ArrayList<>();//资产ID
    private Activity content;
    private EditText et_num;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.back);
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        content = this;
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        lv_data.clear();
        data.clear();
        init();
        initRFID();
    }

    private void init() {
        et_num = (EditText) findViewById(R.id.et_num);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("归还");
        site_tv = (TextView) findViewById(R.id.site_tv);
        site = (LinearLayout) findViewById(R.id.site);
        site.setOnClickListener(v -> {
            Intent intent = new Intent(content, Shift_site.class);
            startActivityForResult(intent, 3);
        });
        uploads = (Button) findViewById(R.id.add);
        lv_list = (ListView) findViewById(R.id.fragment2_list);
        scan_img = (Button) findViewById(R.id.scan_img);
        scan_img.setOnClickListener(v -> {
            startQrCode();
        });
        imageView = (ImageView) findViewById(R.id.fh);
        imageView.setOnClickListener(v -> {
            finish();
        });
        et_num.setFocusableInTouchMode(true);
        et_num.requestFocus();
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i = 0; i < data.size(); i++) {
                    if (S.equals(data.get(i).getCode_number())) {
                        showToast("该资产已存在列表");
                        return;
                    }
                }
                if (!et_num.getText().toString().trim().equals("") && et_num.length() > 9) {
                    if (!lv_data.contains(et_num.getText().toString().trim())) {
                        scanAsset(et_num.getText().toString().trim());
                    } else {
                        showToast("请勿重复扫码");
                    }
                } else {
//                    showToast("错误的格式");
                }
            }
        });
        lv_list.setOnItemLongClickListener((parent, view, position, id) -> {
            new AlertView(" 提示！", "是否删除", "取消", new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position1) {
                    //取消：position1=-1,确定 position1=0
                    if (position1 == 0) {
                        lv_data.remove(data.get(position).getCode_number());
                        data.remove(position);
                        Input_Adapter_item_new adapter_item = new Input_Adapter_item_new(content, R.layout.input_adapter_item, data);
                        lv_list.setAdapter(adapter_item);
                    }
                }
            }).setCancelable(true).show();
            return true;
        });

        uploads.setOnClickListener(v -> {
            if (data.size() <= 0) {
                showToast("请扫码需要归还的资产");
                return;
            }
            if (site_id.equals("")) {
                showToast("请选择存放位置后上传");
                return;
            }
            new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position == 0) {
                        numbers.clear();
                        for (int i = 0; i < data.size(); i++) {
                            numbers.add(data.get(i).getCode_number());
                        }
                        updata();
                    }
                }
            }).setCancelable(true).show();
        });
        btn_rfid = findViewById(R.id.btn_rfid);
        btn_rfid.setOnClickListener(v -> {
            String rfidTitle = btn_rfid.getText().toString();
            if (rfidTitle.equals("开始读取")) {
                rfidClientUtil.read();
            } else {
                rfidClientUtil.stop();
            }
        });
    }

    public void readAsset(String epc) {
        Map<String, String> map = new HashMap<>();
        map.put("rfid", epc);


        Log.d("蒋剑华====", "epc: " + epc);

//        post(url, map, responseData -> handleResponseData(responseData), () -> {
//            this.map.remove(epc);
//        });


        newPost("这个是华哥新增的", map, data -> {

            Log.d("这个是扫码自制接口返回的数据", "data: " + data);
            handleResponseData(data);

        });

    }

    public void scanAsset(final String code) {
        Map<String, String> map = new HashMap<>();
        map.put("rfid", code);
//        post(url, map, responseData ->
//                handleResponseData(responseData)
//        );

        newPostSao("这个是华哥新增的", map, data -> {

            Log.d("这个是扫码自制接口返回的数据", "data: " + data);
            handleResponseData(data);

        });

    }

    private void handleResponseData(String responseData) {
        LogUtils.d(responseData);
        try {
            JSONObject json = new JSONObject(responseData);
            if (json.getString("state").equals("1")) {
                JSONObject jsonObject = json.getJSONObject("asset");
                String assetName = jsonObject.getString("assetName");
                String deptId = jsonObject.getString("deptId");
                String assetNumber = jsonObject.getString("assetNumber");
                if (lv_data.contains(assetNumber)) {
                    showToast("此资产已存在列表");
                    return;
                }
                lv_data.add(assetNumber);
                String userId = jsonObject.getString("userId");
                String model = jsonObject.getString("model");
                String type = jsonObject.getString("type");
                String rfid = jsonObject.getString("rfid");
                String jifang = jsonObject.getString("financialCode");
                String jigui = jsonObject.getString("accountant");
                String image = "";
                if (!TextUtils.isEmpty(jsonObject.getString("image"))) {
                    image = "http://" + Url.IP + jsonObject.getString("image");
                    LogUtils.d(image);
                }
                data.add(0, new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, rfid, jifang, jigui));
                Input_Adapter_item_new adapter_item = new Input_Adapter_item_new(content, R.layout.input_adapter_item, data);
                runOnUiThread(() -> {
                    lv_list.setAdapter(adapter_item);
                    Toast.makeText(content, "添加成功", Toast.LENGTH_SHORT).show();
                });
            }
            if (json.getString("state").equals("0")) {
                showToast("添加失败，请检查服务器");
            } else if (json.getString("state").equals("2")) {
                showToast("添加失败，此资产不存在");
            } else if (json.getString("state").equals("3")) {
                showToast("添加失败，此资产已归还");
            } else if (json.getString("state").equals("4")) {
                showToast("添加失败，资产未领用");
            } else if (json.getString("state").equals("5")) {
                showToast("资产领用单未复审");
            }else if (json.getString("state").equals("999")) {
                showToast("当前资产已经被报废");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        if (requestCode == 3 && resultCode == 3) {
            site_tv.setText(datas.getExtras().getString("site_name"));
            site_id = datas.getExtras().getString("site_id");
            Log.i("333333333333", site_id);
        }
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = datas.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            for (int i = 0; i < data.size(); i++) {
                if (scanResult.equals(data.get(i).getCode_number())) {
                    showToast("该资产已存在列表");
                    return;
                }
            }
            if (!lv_data.contains(scanResult)) {
                scanAsset(scanResult);
            } else showToast("请勿重复扫码");
        }
    }

    private void updata() {
        showDialog("提交数据");
        Map<String, String> map = new HashMap<>();
        map.put("userId", Since_case.getInstance().getUserId());
        map.put("place", site_id);
//        map.put("receivesId", MyDataBase.init(back.this).receivesDetailDao().getAssetByIds(numbers.toString()));
        map.put("assetNumbers", numbers.toString());
//        post(returnAdd, map, responseData -> {
//            LogUtils.d(responseData);
//            handleSubmitData(responseData);
//        }, () -> {
//            canDialog();
//        });

        newPost("这个是华哥新增的提交接口", map, responseData -> {
            handleSubmitData(responseData);
//            Log.d("提交之后的数据", "responseData: " + responseData);
        }, ()->{
            canDialog();
        });
    }

    private void handleSubmitData(final String responseData) {
        try {
            JSONObject jsonObject = new JSONObject(responseData);
            if (jsonObject.getString("state").equals("1")) {

                // TODO: 2023/12/7 怎么判断领用单是否全部归还
                //第一步： 首先肯定要知道获的对应的领用单
                //第二步：获取到领用单对应的申请里面的物资数量
                //第三步：获取到对应领用单中，已经归还的物资有多少个
                //第四步：知道两个数量，对比他们   领用单中要领用的数量 - 对应领用单中归还的数量 = 0 ？全部归还 ：部分归还
                //改领用单中的isreturn的状态为1
                //改领用详情里面的isretrun的状态为1
//                Map<String, String> map = new HashMap<>();
//                map.put("assetNumbers", numbers.toString());
//                String assetNumbers = map.get("assetNumbers").toString();
//                assetNumbers = assetNumbers.substring(1, assetNumbers.length() - 1);
//                assetNumbers = assetNumbers.replace(" ", "");
//                String[] numberList = assetNumbers.split(",");
//                List<String> receviesId = new ArrayList<>();
////                List<Returns> ReturnsList = new ArrayList<>();
//                for (String number : numberList) {
//                    Log.d("这个是number", "number: " + number);
//                    MyDataBase.init(back.this).receivesDetailDao().updateFlag("1", "1", number);
//                    List<String> recevies_id = MyDataBase.init(back.this).receivesDetailDao().getIdById(number);
//                    for (String receviesBean : recevies_id) {
//
//                        if (!recevies_id.contains(receviesBean)) {
//                            receviesId.add(receviesBean);
//                        }
//
//                    }
//                }
//
//                Log.d("这个是什么,看一下","receviesId: " + receviesId);



                lv_data.clear();
                data.clear();
                numbers.clear();
                Input_Adapter_item_new adapter_item = new Input_Adapter_item_new(content, R.layout.input_adapter_item, data);
                runOnUiThread(() -> {

                    lv_list.setAdapter(adapter_item);
                    showToast("提交成功");
                });
            }else if (jsonObject.getString("state").equals("2")) {
                showToast("当前资产已经归还");
                canDialog();
                return;
            }else {
                showToast("提交失败,请重新提交");
                canDialog();
            }
        } catch (JSONException e) {
            showToast("数据解析异常");
            e.printStackTrace();
        } finally {
            canDialog();
        }
    }

    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }


    private RFIDClientUtil rfidClientUtil;
    private Map<String, String> map = new HashMap<>();

    private void initRFID() {
        MyRFIDHandle myRFIDHandle = new MyRFIDHandle();
        myRFIDHandle.post(() -> {
            rfidClientUtil = new RFIDClientUtil(epc -> {
                if (map.containsKey(epc)) {
                    return;
                }
                if(epc!=null&&epc.length()>16) {
                    epc = epc.substring(0, 16);
                }
                map.put(epc, "");
                readAsset(epc);
                //RFID(epc);
            });
            rfidClientUtil.setRequestStop(() -> runOnUiThread(() -> {
                btn_rfid.setText("开始读取");
            }));
            rfidClientUtil.setRequestRead(() -> runOnUiThread(() -> {
                btn_rfid.setText("停止读取");
            }));
            getLifecycle().addObserver(myRFIDHandle);
            getLifecycle().addObserver(rfidClientUtil);
        });
    }
}
